iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
自我挑戰組

利用 node.js/express 架設網站系列 第 9

Day-09 資料庫整合與進階查詢操作

  • 分享至 

  • xImage
  •  

今天一樣有三個重點:
1.整合關聯式資料庫
2.ORM(物件關聯映射)工具
3.進階查詢操作

整合關聯式資料庫

前幾天已經學習了SQLite 或 MongoDB 等輕量級資料庫,今天將學習如何使用更強大的關聯式資料庫如 MySQL 或 PostgreSQL,並將其與 Express 應用整合。

  • MySQL 安裝

    • sudo apt-get install mysql-server
  • PostgreSQL 安裝

    • sudo apt-get install postgresql postgresql-contrib
  • 安裝 MySQL 驅動

    • npm install mysql2
  • 安裝 PostgreSQL 驅動

    • npm install pg

基本資料庫操作

在完成安裝後,你可以開始編寫程式來連接並操作資料庫。
範例:

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'my_database'
});

// 連接數據庫
connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
});

// 查詢數據
connection.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log(results);
});

使用 ORM 工具簡化數據庫操作

手動編寫 SQL 查詢雖然有效,但在大型應用中,使用 ORM 工具如 Sequelize 來管資料庫操作會更加高效且可維護。Sequelize 支持多種資料庫(包括 MySQL 和 PostgreSQL),並且提供了類似 JavaScript 物件的查詢方式,減少了手寫 SQL 的需求。

  • 安裝 Sequelize

    • npm install sequelize mysql2
  • 設置 Sequelize

const { Sequelize, DataTypes } = require('sequelize');

// 初始化 Sequelize 實例
const sequelize = new Sequelize('my_database', 'root', 'password', {
  host: 'localhost',
  dialect: 'mysql'  // 或 'postgres' 對應 PostgreSQL
});

// 定義數據模型
const User = sequelize.define('User', {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false
  }
}, {
  // 其他模型配置
});

// 同步模型到資料庫
sequelize.sync()
  .then(() => {
    console.log('Database & tables created!');
  });

這段代碼展示了如何使用 Sequelize 定義一個 User 模型,並將其同步到資料庫。

  • 使用 Sequelize 進行數據操作
    Sequelize 提供了簡單的 API 來進行數據的增刪改查操作,無需手寫 SQL 語句。
    • 創建用戶:
    User.create({
      name: 'John Doe',
      email: 'john@example.com'
    }).then(user => {
      console.log('User created:', user);
    });
    
    • 查詢用戶:
    User.findAll().then(users => {
      console.log('All users:', users);
    });
    
    • 更新用戶:
    User.update({ name: 'Jane Doe' }, {
      where: {
        id: 1
      }
    }).then(() => {
      console.log('User updated');
    });
    

上一篇
Day-08 express API開發(下)
下一篇
Day-10 用戶驗證與授權
系列文
利用 node.js/express 架設網站26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言